<?php
class Model_contact extends Model {
    function Model_contact() {
        parent::Model();
        $this->fromSession = $this->usersession->currentUser();
    }


    function bringContact($data) {
        $this->db->flush_cache();
        if ($data["person_id"] <= 0) {
            $result['priority'] = '0';
            $result['available'] = '1';
            $result['clients_id'] = '1';
        }


        if ($data["person_id"] > 0) {
            $this->db->select("persons.*,domain.name as domain_name,subD.name as domain_sub_name,city.name as city_name,county.name as county_name,position.name as position_name,subP.name as position_sub_name,division.name as division_name, userCreate.name as create_name,userMod.name as user_modified,userMod2.name as user_modified2,clients_id, trust.name as trust_name ", false);
            $this->db->join("domain", "domain.domain_id=persons.domain_id", "left");
            $this->db->join("domain subD", "subD.domain_id=persons.domain_sub_id", "left");

            //$this->db->join("client_persons_group"," client_persons_group.person_id=persons.person_id and persons.person_id=".$data['person_id']." ","inner");
            //query care imi aduce id-urile campaniilor unui contact ordonate desc in functie de data introducerii si despartite prin separator "=" pentru a putea fi compatibile cu lovcombo
            $this->db->join(" (select `client_persons`.`person_id` ,group_concat(distinct `client_persons`.`client_id` order by `client_persons`.`update_date` DESC separator '=') AS `clients_id`
	from `client_persons` where `client_persons`.`extern` = 0 AND  person_id=" . $data['person_id'] . " group by `client_persons`.`person_id` order by `client_persons`.`update_date` desc) CC", " CC.person_id=persons.person_id ", "LEFT");

            $this->db->join("position", "position.position_id=persons.position_id", "left");
            $this->db->join("position subP", "subP.position_id=persons.position_sub_id", "left");

            $this->db->join("city", "city.city_id=persons.city_id", "left");
            $this->db->join("division", "division.division_id=persons.division_id", "left");
            $this->db->join("county", "county.county_id=persons.county_id", "left");
            $this->db->join("trust","trust.trust_id=persons.trust_id","left");
            $this->db->join("user userCreate", "userCreate.user_id=persons.create_by", "left");
            $this->db->join("user userMod", "userMod.user_id=persons.modify_by", "left");
            $this->db->join("user userMod2", "userMod2.user_id=persons.modify_by2", "left");

            $this->db->where("persons.person_id", $data['person_id']);
            $query = $this->db->get('persons');
            $result = $query->row_array();
        }

        return $result;

    }

    function saveContact($data) {

        $person_id = $data['person_id'];
        unset($data['person_id']);


        $data["lname"] = strTitle($data["lname"]);
        $data["fname"] = strTitle($data["fname"]);
        $data["company"] = strUpper($data["company"]);
        $data["address"] = strTitle($data["address"]);
        $data["country"] = strTitle($data["country"]);
        $data["web"] = strLower($data["web"]);
        if ($data["birth"] == "") {
            $data["birth"] = null;
        }
        if ($data['available'] == 'on') {
            $data['available'] = 1;
        }
        else {
            $data['available'] = 0;
            $data['priority'] = 0;
        }

        /*if ($data['send_mail'] == 'on') $data['send_mail'] = 1;
        else $data['send_mail'] = 0;*/
        //$data["clients_id"]="=".$data["client_id"]."="; //variabila unde se tin id-urile trimise prin Ext


        //update         
        if ($person_id > 0) {

            $this->db->flush_cache();
            $this->db->where('person_id', $person_id);
            $this->db->update('persons', $data);

            if ($this->db->affected_rows() > 0) {

                $this->db->flush_cache();
                $this->db->where('person_id', $person_id);
                $result = $this->db->get('persons')->row_array();


                //adaugare date despre ultimele modificari ale userilor daca nu sunt admini
                //corector invizibil pentru admin
                if ($this->fromSession["level"] != "supervisor") {
                    $dayRule = date("Y-m-d", strtotime(date("Y-m-d", strtotime($result["date_modified2"])) . "+30 days"));
                    if (date("Y-m-d") > $dayRule) {
                        $data["modify_by2"] = $result["modify_by"];
                        $data["date_modified2"] = $result["date_modified"];
                        $data["modify_by"] = $this->fromSession["user_id"];
                        $data["date_modified"] = date("Y-m-d H:i:s");
                    }
                    else {
                        $data["modify_by"] = $this->fromSession["user_id"];
                        $data["date_modified"] = date("Y-m-d H:i:s");
                    }
                }

                $this->db->flush_cache();
                $this->db->where('person_id', $person_id);
                $this->db->update('persons', $data);
            }
            return $person_id;
        }

        //insert
        if ($person_id < 0) {
            $data["modify_by"] = $this->fromSession["user_id"];
            $data["date_modified"] = date("Y-m-d H:i:s");
            $data["modify_by2"] = $this->fromSession["user_id"];
            $data["date_modified2"] = date("Y-m-d H:i:s");
            $data["create_by"] = $this->fromSession["user_id"];
            $data["date_created"] = date("Y-m-d H:i:s");

            $this->db->flush_cache();
            $this->db->insert('persons', $data);
            return $this->db->insert_id();
        }

    }

    function saveContact2($iPersonId, $data) {

        $sDataClient = $data["client_id"]; //creare variabila temp
        if ($sDataClient != "") {

            $aDataClient = explode("=", $sDataClient);
            $aContactClient = array();

            //se scot campaniile care deja apartin de contact
            $this->db->flush_cache();
            $this->db->where("person_id", $iPersonId);
            $this->db->order_by("client_persons_id", "desc");
            $aResult = $this->db->get("client_persons")->result_array();

            foreach ($aResult as $aClient) {
                $aContactClient[] = $aClient["client_id"];
            }

            //se cauta care campanii sunt noi
            $aClientNew = array_diff($aDataClient, $aContactClient);
            //se cauta care campanii au fost scoase
            $aClientDel = array_diff($aContactClient, $aDataClient);

            //se insereaza campaniile noi
            foreach ($aClientNew as $iClientNew) {
                $this->db->flush_cache();
                $temp = array("person_id" => $iPersonId, "client_id" => $iClientNew);
                $this->db->insert("client_persons", $temp);
            }
            //se sterg campaniile care nu se mai trimit prin POST
            foreach ($aClientDel as $iClientNew) {
                $this->db->flush_cache();
                $this->db->where("person_id", $iPersonId);
                $this->db->where("client_id", $iClientNew);
                $this->db->delete("client_persons");
            }

            //update despre userii care au modificat contactul daca nu sunt admini
            if (((count($aClientNew) > 0) || (count($aClientDel))) && ($this->fromSession["level"] != "admin")) {

                $this->db->flush_cache();
                $this->db->where('person_id', $iPersonId);
                $result = $this->db->get('persons')->row_array();

                $data = array();
                $dayRule = date("Y-m-d", strtotime($result["date_modified2"]) . "+30 days");

                if (date("Y-m-d") > $dayRule) {
                    $data["modify_by2"] = $result["modify_by"];
                    $data["date_modified2"] = $result["date_modified"];
                    $data["modify_by"] = $this->fromSession["user_id"];
                    $data["date_modified"] = date("Y-m-d H:i:s");
                }
                else {
                    $data["modify_by"] = $this->fromSession["user_id"];
                    $data["date_modified"] = date("Y-m-d H:i:s");
                }

                $this->db->flush_cache();
                $this->db->where('person_id', $iPersonId);
                $this->db->update('persons', $data);
            }
        }

        //se extrage ultima campanie contactului
        $this->db->flush_cache();
        $this->db->select("client.*", false);
        $this->db->where("person_id", $iPersonId);
        $this->db->join("client", "client.client_id=client_persons.client_id", "inner");
        $this->db->order_by("client_persons_id", "desc");
        $aClient = $this->db->get("client_persons")->row_array();

        $aTemp = array("client_id" => $aClient["client_id"], "client_name" => $aClient["name"]);
        $this->db->flush_cache();
        $this->db->where("person_id", $iPersonId);
        $result = $this->db->update("persons", $aTemp);

        return $result;
    }


    /**
     * Functie care verifica existenta unui duplicat
     */
    function _existsContact($data) {
        $this->db->flush_cache();
        $this->db->where("lower(lname)", strLower($data["lname"]));
        $this->db->where("lower(fname)", strLower($data["fname"]));
        $this->db->where("upper(company)", strUpper($data["company"]));
        $this->db->where("upper(address)", strUpper($data["address"]));
        $this->db->where("person_id !=", $data['person_id']);
        $query = $this->db->get("persons");

        if ($query->num_rows() == 0) {
            return false;
        }
        else {
            return true;
        }
    }


    function modifyContact($data) {

        $persons_id = json_decode($data["modify_4_users"]);
        foreach ($persons_id as $person) $person_id[] = $person->id;

        $this->db->flush_cache();
        $this->db->where_in("person_id", $person_id);

        $dataUpdate = array();
        if ($data["corector_company"] != '') $dataUpdate["company"] = mb_convert_case($data["corector_company"], MB_CASE_UPPER, "UTF-8");
        if ($data["corector_domain"] != '') $dataUpdate["domain_id"] = $data["corector_domain"];
        if ($data["corector_domain_sub"] != '') $dataUpdate["domain_sub_id"] = $data["corector_domain_sub"];
        if ($data["corector_city"] != '') $dataUpdate["city_id"] = $data["corector_city"];
        if ($data["corector_county"] != '') $dataUpdate["county_id"] = $data["corector_county"];
        if ($data["corector_lname"] != '') $dataUpdate["lname"] = strTitle($data["corector_lname"]);
        if ($data["corector_fname"] != '') $dataUpdate["fname"] = strTitle($data["corector_fname"]);
        if ($data["corector_address"] != '') $dataUpdate["address"] = strTitle($data["corector_address"]);
        if ($data["corector_address2"] != '') $dataUpdate["address2"] = $data["corector_address2"];
        if ($data["corector_email"] != '') $dataUpdate["email"] = strLower($data["corector_email"]);
        if ($data["corector_email2"] != '') $dataUpdate["email2"] = strLower($data["corector_email2"]);
        if ($data["corector_phone"] != '') $dataUpdate["phone"] = $data["corector_phone"];
        if ($data["corector_mobil"] != '') $dataUpdate["corector_mobil"] = $data["corector_mobil"];
        if ($data["corector_web"] != '') $dataUpdate["web"] = strLower($data["corector_web"]);
	    if ($data["corector_zona"] != '') $dataUpdate["zona"] = $data["corector_zona"];
	    if ($data["corector_rate"] != '') $dataUpdate["rate"] = $data["corector_rate"];
	    if ($data["corector_periodicitate"] != '') $dataUpdate["periodicitate"] = $data["corector_periodicitate"];
	    if ($data["corector_trust"] != '') $dataUpdate["trust_id"] = $data["corector_trust"];
		if ($data["corector_card_suma"] != '') $dataUpdate["rate_suma"] = $data["corector_card_suma"];
		if ($data["corector_tiraj_vizitatori"] != '') $dataUpdate["tiraj"] = $data["corector_tiraj_vizitatori"];
		

        if (count($dataUpdate) > 0) $query = $this->db->update("persons", $dataUpdate);
    }

    function dezactivateContact($data) {

        $persons_id = json_decode($data["contacts"]);

        foreach ($persons_id as $person) {
            $aContacts[] = $person;
        }

        $dataUpdate = array();
        if ($data["op"] == '0') {
            $this->db->flush_cache();
            $this->db->where_in("person_id", $aContacts);
            $dataUpdate = array("available" => 0, "priority" => "0");
            $query = $this->db->update("persons", $dataUpdate);
        }
        if ($data["op"] == '1') {
            $this->db->flush_cache();
            $this->db->where_in("person_id", $aContacts);
            $dataUpdate = array("available" => 1);
            $query = $this->db->update("persons", $dataUpdate);
        }
        if ($data["op"] == '10') {

            if (in_array("1", $aContacts)) {
                return false;
            }

            $this->db->flush_cache();
            $this->db->where_in("person_id", $aContacts);
            $query = $this->db->delete("persons");
            //stergerea se va afectua si in tabela client_persons ( mapare campanie - contact)            
        }
        return $query;
    }


    function bringClient($data) {

        $aTemp = $aTemp2 = array();

        $this->db->flush_cache();
        $this->db->select("client_persons.client_id as id,name");
        $this->db->where("person_id", $data["iContactId"]);
        $this->db->join("client", "client.client_id=client_persons.client_id", "inner");
        $this->db->order_by("client_persons_id", "desc");
        $aResult = $this->db->get("client_persons")->result_array();

        foreach ($aResult as $aClient) {
            $aTemp[] = $aClient["id"];
        }

        $this->db->flush_cache();
        if (count($aTemp) > 0) {
            $this->db->where_not_in("client_id", $aTemp);
        }
        $this->db->select("client_id as id, name", false);
        $this->db->order_by('name', 'asc');
        $aTemp2 = $this->db->get("client")->result_array();

        $aTemp = array_merge($aResult, $aTemp2);
        return $aTemp;
    }

    function makeCopy($data) {

        $this->db->flush_cache();
        $this->db->where("create_by", $this->fromSession["user_id"]);
        $this->db->delete("copy");

        $dataInsert = array(
            "phone" => $data["phone"], "name" => $data["name"], "create_by" => $this->fromSession["user_id"],
            "mobil" => $data["mobil"], "company" => $data["company"], "city_id" => $data["city_id"],
            "country" => $data["country"],  "county_id" => $data["county_id"],
            "domain_id" => $data["domain_id"], "domain_sub_id" => $data["domain_sub_id"], "address" => $data["address"],
            "address2" => $data["address2"], "web" => $data["web"],
            "obs_company" => $data["obs_company"],
            "email2" => $data["email2"]

        );
        $this->db->insert('copy', $dataInsert);
    }

    function getCopy($data) {

        $this->db->select("copy.*,domain.name as domain_name,subD.name as domain_sub_name,city.name as city_name,county.name as county_name,web,email2", false);
        $this->db->join("domain", "domain.domain_id=copy.domain_id", "left");
        $this->db->join("domain subD", "subD.domain_id=copy.domain_sub_id", "left");
        $this->db->join("city", "city.city_id=copy.city_id", "left");
        $this->db->join("county", "county.county_id=copy.county_id", "left");
        $this->db->where("create_by", $this->fromSession["user_id"]);
        $query = $this->db->get('copy');
        $result = $query->result_array();
        return $result;
    }

    function deleteCopy($data) {
        $this->db->where("copy_id", $data['copy_id']);
        $this->db->delete("copy");
    }

    /**
     * Mutare / stergere de pe o campanie pe baza unui id
     * @param $aData
     * @return void
     */
    function moveId($aData) {

        $sDescription = "";
        $aContact = explode("\n", $aData["id"]);
        		

        if ($aData["op"] == "delete") {
            $this->db->where_in("person_id", $aContact);
            $this->db->where("client_id", $aData["client_id"]);
            $this->db->where("extern", 0);
            $this->db->delete("client_persons");
        }

        if ($aData["op"] == "add") {
            foreach ($aContact as $key => $aContactRec) {
                //eliminare id-uri nule
                if ($aContactRec == "") {
                    unset($aContact[$key]);
                    continue;
                }

                //verificare daca exista in baza de date
                $this->db->flush_cache();
                $this->db->where("person_id", $aContactRec);
                $aQuery = $this->db->get("persons");

                if ($aQuery->num_rows() == 0) {
                    $sDescription .= $aContactRec . " ";
                    continue;
                }
				
				$dezabonare = 0;
			
				//daca se doreste pastrarea dezabonarii 
				if ($aData["dezabonare"] == 1) { 
					//se cauta dezabonarea de pe clientul de baza	
					$this->db->flush_cache();
					$this->db->select("unsubscribed");
	                $this->db->where("person_id", $aContactRec);
					$this->db->where("unsubscribed",1);
	                $this->db->where_in("client_id",explode("=",$aData["base_client_id"])) ;
	                $aQuery = $this->db->get("client_persons");
					
					if($aQuery->num_rows()) {
						$dezabonare = 1;
					} 					
				} 
				
                //verificare daca exista in client_persons
                $this->db->flush_cache();
                $this->db->where("person_id", $aContactRec);
                $this->db->where("client_id",$aData["client_id"]) ;
                $aQuery = $this->db->get("client_persons");

                //exista deja
                if ($aQuery->num_rows() > 0) {
                	//daca exista atunci schimb statusul dezabonare daca este cazul
                	if($dezabonare == 1) {
                		$aTemp = $aQuery->row_array();
	                	$this->db->set("unsubscribed",1);
						$this->db->where("client_persons_id",$aTemp["client_persons_id"]);
						$this->db->update("client_persons");
					}
                    continue;
                } else {
                	$this->db->flush_cache();
	                $temp = array("person_id" => $aContactRec, "client_id" => $aData["client_id"], "unsubscribed" => $dezabonare );
	                $this->db->insert("client_persons", $temp);
                }	               
            }
        }

        foreach ($aContact as $aContactRec) {
            //se extrage ultima campanie contactului
            $this->db->flush_cache();
            $this->db->select("client.*", false);
            $this->db->where("person_id", $aContactRec);
            $this->db->join("client", "client.client_id=client_persons.client_id", "inner");
            $this->db->order_by("client_persons_id", "desc");
            $aClient = $this->db->get("client_persons")->row_array();

            $aTemp = array("client_id" => $aClient["client_id"], "client_name" => $aClient["name"]);
            $this->db->flush_cache();
            $this->db->where("person_id", $aContactRec);
            $this->db->update("persons", $aTemp);
        }
        return $sDescription;
    }
}